package com.nav.rummy.core;
import java.util.ArrayList;

public class Sequence extends ArrayList<Card> implements IArrangement {
	private static final long serialVersionUID = 1L;
	private Card joker;
	private boolean NO_MORE = false;

	public Sequence(Card joker) {
		this.joker = joker;
	}

	public boolean add(Card card) {
		if (canAdd(card))
			return super.add(card);
		return false;
	}

	private Rank getNextRank() {
		Rank r = null;
		for (int i = size() - 1; i >= 0; i--) {
			Card c = get(i);
			if (joker == null || joker.getRank() != c.getRank()) {
				r = c.getRank();
				for (int j = i; j < size(); j++)
					r = r.nextInSequence();
			}
		}
		if (r == Rank.DEUCE && size() > 1) {
			NO_MORE = true;
			r = null;
		}
		return r;
	}

	private Suit getNextSuit() {
		for (Card c : this) {
			if (joker == null || joker.getRank() != c.getRank())
				return c.getSuit();
		}
		return null;
	}

	public boolean canAdd(Card card) {
		if (card == null)
			return false;
		if (size() == 0 || joker != null && card.getRank() == joker.getRank())
			return true;
		Rank r = getNextRank();
		if (NO_MORE)
			return false;
		Suit s = getNextSuit();
		return (r == null || r == card.getRank())
				&& (s == null || s == card.getSuit());
	}
}
